#include<stdio.h>
#include <stdlib.h>
#include <string.h>

#define MAX_SIZE 100       //定义顺序表最大长度

typedef struct
{
    int data[MAX_SIZE];      //存储顺序表的数组
    int length;              //当前顺序表的长度
}sqlist_t;

sqlist_t *sqlist_init(void){
    sqlist_t *list = (sqlist_t *)malloc(sizeof(sqlist_t));
    list -> length = 0;
    memset(list->data,0,MAX_SIZE);
    return list;
}

int sqlist_insert(sqlist_t *list, int index, int value){
    if(index < 1 || index > list -> length + 1 || list -> length >= MAX_SIZE) {
        return -1;
    }
    for(int i = list -> length-1 ; i >= index-1 ; i--) {
        list -> data[i+1] = list -> data[i];
    }
    list -> data[index-1] = value;
    list -> length++;
    return 0;
}

int sqlist_delete(sqlist_t *list,int index,int *value) {
    if(index < 1 || index > list -> length) {
        return -1;
    }
    *value = list->data[index-1];
    for(int i=index-1;i<list->length-1;++i) {
        list->data[i]=list->data[i+1];
    }
    list->length--;
    return 0;
}

int sqlist_modify(sqlist_t *list,int index,int value) {
    if(index < 1 || index > list -> length) {
        return -1;
    }
    list->data[index-1] = value;
    return 0;
}

int sqlist_locate(sqlist_t *list,int value) {

    if(list->length>MAX_SIZE) {
        return -1;
    }

    for(int i=0;i<list->length;++i) {
        if(list->data[i]==value) {
            return i+1;
        }
    }
    return 0;
}

int sqlist_print(sqlist_t *list) {
    for(int i=0;i<list->length;++i) {
        printf("%d ",list->data[i]);
    }
    printf("\n");
}

int sqlist_reserve(sqlist_t *list) {
    for(int i=0;i<list->length/2;++i) {
        int t = list->data[i];
        list->data[i] = list->data[list->length-1-i];
        list->data[list->length-1-i] = t;
    }
    return 0;
}

int main(int argc,char const *argv[]) {
    sqlist_t *L = sqlist_init();
    printf("创建数据表：\n");
    for(int i=0;i<5;++i) {
        sqlist_insert(L,i+1,i+1);
    }
    sqlist_print(L);

    printf("插入数据：\n");

    sqlist_insert(L,3,6);
    sqlist_print(L);
    printf("删除数据：\n");
    int value;
    sqlist_delete(L,3,&value);
    printf("%d\n",value);
    sqlist_print(L);
    printf("修改数据：\n");
    sqlist_modify(L,1,5);
    sqlist_print(L);
    printf("查找数据：\n");
    int index = sqlist_locate(L,5);
    printf("%d\n",index);
    printf("翻转数据：\n");
    sqlist_reserve(L);
    sqlist_print(L);
}